package com.linkage.jz.bankruptcy.activity.Main;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Msg.MsgDetailActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingEmailActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingReadMeActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.GetPwdOneActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.PhoneLoginActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A login screen that offers login via email/password.
 */
public  class RateCalcActivity extends BaseActivity implements OnClickListener{
    private static final String TAG = PersonSettingReadMeActivity.class.getSimpleName();
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();
    private ShapeLoadingDialog shapeLoadingDialog ;
    int date_type =1;
    private ArrayList<View> editViews = new ArrayList<View>();
    private LinearLayout linearLayout1;
    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

        top_back.setOnClickListener(this);
        btn_reset.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        top_title = findViewById(R.id.top_title);
        top_title.setText("利息计算器");
        top_mune.setVisibility(View.INVISIBLE);
        linearLayout1 = findViewById(R.id.linearLayout1);
    }




    TextView top_title,tv_stime,tv_etime,tv_type,calc_ret,calc_ret2,calc_ret3,tv_rate,tv_bankrate,calc_ret2_1;
    Button top_back,top_mune,btn_calc,btn_reset;
    RelativeLayout rl_money,re_stime,re_etime,re_type,rl_rate,rl_overrate;
    EditText item_money,item_rate,item_overrate;
    LinearLayout showrate,ll_calc_ret;
    @Override
    public void initView() {
        //登录层、下拉层、其它登录方式层

        top_mune = findViewById(R.id.top_mune);
        rl_overrate = findViewById(R.id.rl_overrate);
        item_overrate = findViewById(R.id.item_overrate);
        showrate = findViewById(R.id.showrate);
        ll_calc_ret = findViewById(R.id.ll_calc_ret);
        btn_reset =findViewById(R.id.btn_reset);

        top_back = findViewById(R.id.top_back);
        top_title = findViewById(R.id.top_title);
        calc_ret = findViewById(R.id.calc_ret);
        calc_ret2 = findViewById(R.id.calc_ret2);
        calc_ret3 = findViewById(R.id.calc_ret3);
//        calc_ret2_1 = findViewById(R.id.calc_ret2_1);

        tv_stime = findViewById(R.id.tv_stime);
        tv_etime = findViewById(R.id.tv_etime);
        tv_type = findViewById(R.id.tv_type);
        btn_calc = findViewById(R.id.btn_calc);
        rl_money = findViewById(R.id.rl_money);
        re_stime = findViewById(R.id.re_stime);
        re_etime = findViewById(R.id.re_etime);
        re_type = findViewById(R.id.re_type);
        tv_bankrate =findViewById(R.id.tv_bankrate);

        tv_bankrate.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tv_bankrate.getPaint().setAntiAlias(true);

        rl_rate = findViewById(R.id.rl_rate);
        item_money = findViewById(R.id.item_money);
        item_rate = findViewById(R.id.item_rate);
        rl_rate.setVisibility(View.GONE);
        tv_rate = findViewById(R.id.tv_rate);
        tv_rate.setVisibility(View.GONE);

        item_rate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                        textView.setText(s.toString());

                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });


        tv_etime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                        textView.setText(s.toString());

                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });


        tv_stime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                        textView.setText(s.toString());

                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });



        item_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                        textView.setText(s.toString());

                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        item_overrate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                        textView.setText(s.toString());

                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });


        showrate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MsgDetailActivity msgDetailActivity = new MsgDetailActivity();

                Intent intent = new Intent(RateCalcActivity.this, ShowRateListActivity.class);
                startActivity(intent);


            }
        });
        re_stime.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                date_type = 1;
                if(tv_stime.getText().toString().equalsIgnoreCase("")) {
                    setDate("");
                }else{
                    setDate(tv_stime.getText().toString());
                }
            }
        });

        re_etime.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                date_type = 2;
                if(tv_etime.getText().toString().equalsIgnoreCase("")) {
                    setDate("");
                }else{
                    setDate(tv_etime.getText().toString());
                }

            }
        });

        btn_calc.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                try {
                    String sTime = tv_stime.getText().toString();
                    String eTime = tv_etime.getText().toString();
                    String rate = item_rate.getText().toString();
                    String money = item_money.getText().toString();
                    String overrate = item_overrate.getText().toString();

                    if ("".equalsIgnoreCase(money)) {
                        Toast.makeText(RateCalcActivity.this, "请填写本金", Toast.LENGTH_LONG).show();
                        return;
                    }

                    if ("".equalsIgnoreCase(sTime)) {
                        Toast.makeText(RateCalcActivity.this, "请选择起算日期", Toast.LENGTH_LONG).show();
                        return;
                    }

                    if ("".equalsIgnoreCase(eTime)) {
                        Toast.makeText(RateCalcActivity.this, "请选择截止日期", Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (getTimeCompareSize(sTime, eTime) == 1) {
                        Toast.makeText(RateCalcActivity.this, "截止日期不能早于起算日期", Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (type == -1) {
                        Toast.makeText(RateCalcActivity.this, "请选择利率项目", Toast.LENGTH_LONG).show();
                        return;
                    }


                    if ("".equalsIgnoreCase(overrate)) {
                        Toast.makeText(RateCalcActivity.this, "请填写倍率", Toast.LENGTH_LONG).show();
                        return;
                    }




                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date d_stime = sdf.parse(sTime);
                    Date d_etime = sdf.parse(eTime);
                    Long l_stime = d_stime.getTime()/1000;
                    Long l_etime = d_etime.getTime()/1000;
                    CalcData(money, l_stime+"", l_etime+"", type + "", rate, overrate,sTime,eTime);


                }catch (Exception ex)
                {
                    ex.printStackTrace();
                }
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                float f_rate = Float.parseFloat(rate)/100;
//                float f_money = Float.parseFloat(money);
//
//                if(type == 0)
//                {
//                    f_rate = f_rate/360;
//                }else if (type==1)
//                {
//                    f_rate = f_rate/12;
//                }
//
//                try {
//
//                   long getTimeDistance =  getTimeDistance(sdf.parse(sTime), sdf.parse(eTime));
//
//                   float ret = f_money*f_rate* getTimeDistance;
//                    String result = String .format("%.2f",ret);
////                   ret = (float)(ret * 100 )/100;
//                    calc_ret.setText(result+"元 逾期天数："+getTimeDistance);
//                }catch (Exception e)
//
//                    e.printStackTrace();
//                }

            }
        });

        re_type.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                final List<String> values = new ArrayList<String>();

                AlertDialog.Builder builder = new AlertDialog.Builder(RateCalcActivity.this);

                //builder.setIcon(R.drawable.ic_launcher);
                builder.setTitle("请选择");
                //    指定下拉列表的显示数据
                final String[] cities = {"六个月内（含六个月）", "六个月至一年（含一年）","一至三年（含三年）"

                        ,"三年至五年（含五年）"
                        ,"五年以上"
                        ,"自定义利率"};
                //    设置一个下拉的列表选择项
                builder.setItems(cities, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        tv_type.setText(cities[which]);
                        if(which == 5)
                        {
                            rl_rate.setVisibility(View.VISIBLE);
                            tv_rate.setVisibility(View.VISIBLE);
                        }else{
                            rl_rate.setVisibility(View.GONE);
                            tv_rate.setVisibility(View.GONE);
                        }
                        type = which;
                        showSave();
                    }
                });
                builder.show();

            }
        });
        showSave();

    }

    public static void start(Context context) {
        Intent intent = new Intent(context, RateCalcActivity.class);
        context.startActivity(intent);
    }

    private void showSave()
    {
        String str1 =  item_money.getText().toString().trim();
        String str2 =  tv_stime.getText().toString().trim();
        String str3 =  tv_etime.getText().toString().trim();
        int type4 = type;
        String str5 =  item_rate.getText().toString().trim();
        String str6 =  item_overrate.getText().toString().trim();

        if(!str1.equalsIgnoreCase("") &&  !str2.equalsIgnoreCase("")
         &&  !str3.equalsIgnoreCase("") && type4 !=-1 && !str6.equalsIgnoreCase("")
                )


        {
            if(type4 == 5 && !str5.equalsIgnoreCase("")) {
                btn_calc.setClickable(true);
                btn_calc.setBackgroundResource((R.drawable.corner_btn));
            }else{
                btn_calc.setClickable(false);
                btn_calc.setBackgroundResource((R.drawable.corner_nosel_btn));
            }

            if(type4 != 5)
            {
                btn_calc.setClickable(true);
                btn_calc.setBackgroundResource((R.drawable.corner_btn));
            }
        }else{
            btn_calc.setClickable(false);
            btn_calc.setBackgroundResource((R.drawable.corner_nosel_btn));
        }


    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.activity_calcrate);

        initView();
        shapeLoadingDialog = new ShapeLoadingDialog(this);

        type = -1;
        super.onCreate(savedInstanceState);
    }

    //初始化视图


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                //返回
                MainActivity.start(this);
                finish();
                break;
            case R.id.ll_phonelogin:
                PhoneLoginActivity.start(this);
                finish();
                break;
            case R.id.top_back:
                finish();
                break;
            case R.id.getPwd:
                GetPwdOneActivity.start(this);
            case R.id.btn_reset:

                btn_reset.setVisibility(View.GONE);
                ll_calc_ret.setVisibility(View.GONE);
                tv_stime.setText("");
                tv_etime.setText("");
                item_rate.setText("");
                item_money.setText("");
                item_overrate.setText("");
                type = -1;
                tv_type.setText("");
                removeView();

                showSave();
                break;
            default:
                break;
        }
    }


    private int type =1;




    public void setDate(String initdata){

        //通过自定义控件AlertDialog实现
        AlertDialog.Builder builder = new AlertDialog.Builder(RateCalcActivity.this);
        View view = (LinearLayout) getLayoutInflater().inflate(R.layout.layout_dateshow, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        //设置日期简略显示 否则详细显示 包括:星期\周
        datePicker.setCalendarViewShown(false);
        //初始化当前日期
        Calendar calendar = Calendar.getInstance();
        if("".equalsIgnoreCase(initdata)) {
            calendar.setTimeInMillis(System.currentTimeMillis());

        }else{
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date initdate = sdf.parse(initdata);
                calendar.setTime(initdate);
            }catch (Exception ex)
            {
                ex.printStackTrace();
            }

        }
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), null);

        //设置date布局
        builder.setView(view);
        builder.setTitle("设置日期信息");
        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //日期格式
                StringBuffer sb = new StringBuffer();
                sb.append(String.format("%d-%02d-%02d",
                        datePicker.getYear(),
                        datePicker.getMonth() + 1,
                        datePicker.getDayOfMonth()));
//                        oplandate.setText(sb);
//                        //赋值后面闹钟使用
                int mYear = datePicker.getYear();
                int mMonth = datePicker.getMonth();
                int mDay = datePicker.getDayOfMonth();
                if(date_type ==1)
                {
                    tv_stime.setText(sb.toString());
                }else{
                    tv_etime.setText(sb.toString());
                }
                dialog.cancel();
            }
        });
        builder.setNegativeButton("取  消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.create().show();
    }




    /**
     * 获得两个日期间距多少天
     *
     * @param beginDate
     * @param endDate
     * @return
     */
    public  long getTimeDistance(Date beginDate, Date endDate) {
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(beginDate);
        fromCalendar.set(Calendar.HOUR_OF_DAY, fromCalendar.getMinimum(Calendar.HOUR_OF_DAY));
        fromCalendar.set(Calendar.MINUTE, fromCalendar.getMinimum(Calendar.MINUTE));
        fromCalendar.set(Calendar.SECOND, fromCalendar.getMinimum(Calendar.SECOND));
        fromCalendar.set(Calendar.MILLISECOND, fromCalendar.getMinimum(Calendar.MILLISECOND));

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(endDate);
        toCalendar.set(Calendar.HOUR_OF_DAY, fromCalendar.getMinimum(Calendar.HOUR_OF_DAY));
        toCalendar.set(Calendar.MINUTE, fromCalendar.getMinimum(Calendar.MINUTE));
        toCalendar.set(Calendar.SECOND, fromCalendar.getMinimum(Calendar.SECOND));
        toCalendar.set(Calendar.MILLISECOND, fromCalendar.getMinimum(Calendar.MILLISECOND));

        long dayDistance = (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);
        dayDistance = Math.abs(dayDistance);
//        calc_day.setText(dayDistance+"天");
        return dayDistance;
    }



    public static int getTimeCompareSize(String startTime, String endTime){
        int i=0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//年-月-日 时-分
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime()<date1.getTime()){
                i= 1;
            }else if (date2.getTime()==date1.getTime()){
                i= 2;
            }else if (date2.getTime()>date1.getTime()){
                //正常情况下的逻辑操作.
                i= 3;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  i;
    }


    public void CalcData(final String deposit,final String startTime,final String endTime,
                         final String rateType,final String rate,final String speed,final String sTime, final String eTime)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            getToken();
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        removeView();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("token", "")

                .add("deposit", deposit)
                .add("startTime",startTime)
                .add("endTime", endTime)
                .add("rateType", rateType)
                .add("rate", rate)
                .add("speed", speed)
                .build();

        String url = Consts.WEBURL_CALCRATE;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(RateCalcActivity.this,"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();


                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        JSONObject dataobj = object.optJSONObject("data");



                        JSONArray list = dataobj.optJSONArray("list");
//                        double d_tmp = object.optJSONObject("data").optDouble("totalInterest");
                        String strtmp= object.optJSONObject("data").optString("totalInterest");
                        BigDecimal db = new BigDecimal(strtmp);
                        final String totalInterest = db.toPlainString();
//                        final String rate = "";
//                        final String interest = "";

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                try {
                                    for (int i = 0; i < list.length(); i++) {
                                        JSONObject ret = (JSONObject) list.get(i);
                                        final long strsTime = ret.optLong("startTime");
                                        final long streTime = ret.optLong("endTime");
                                        final String days = ret.optString("days");
                                        final String rate = ret.optString("rate");

                                        String strtmp= object.optJSONObject("data").optString("totalInterest");
                                        BigDecimal db = new BigDecimal(strtmp);

                                        final String interest = ret.optString("interest");
                                        addView(strsTime*1000,streTime*1000,days, rate, interest);

                                    }
                                    calc_ret.setText("" + totalInterest + "");
                                }catch ( Exception ex)
                                {
                                    ex.printStackTrace();
                                }
//                                calc_ret2_1.setText(sTime+"至"+eTime+" 共");
//                                calc_ret2.setText(""+days+"");
//                                calc_ret3.setText(""+rate);
                                ll_calc_ret.setVisibility(View.VISIBLE);
                                btn_reset.setVisibility(View.VISIBLE);

//                                Toast.makeText(RateCalcActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
//                                BankruptcyApp.loginInfo.setEmail(email);


                            }



                        });
//                        finish();

                    }else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(RateCalcActivity.this, "提交失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(RateCalcActivity.this, "提交失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }


    private void addView(long strsTime,long streTime,String days,String  rate,String  interest){
        View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.activity_calcrate_item, null);

        TextView calc_ret2 = (TextView)view.findViewById(R.id.calc_ret2);
        TextView calc_ret21 = (TextView)view.findViewById(R.id.calc_ret21);
        TextView calc_ret3 = (TextView)view.findViewById(R.id.calc_ret3);
        TextView calc_ret4 = (TextView)view.findViewById(R.id.calc_ret4);
//        tv_grouptitle2.setText();

         String   tmp1 = Utils.timeStamp2Date(strsTime,"yyyy-MM-dd ");
        String   tmp2 = Utils.timeStamp2Date(streTime,"yyyy-MM-dd ");
        calc_ret2.setText(tmp1+"至"+tmp2);
        calc_ret21.setText(days);
        calc_ret3.setText(rate);
        calc_ret4.setText(interest);


        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        linearLayout1.addView(view, params);

        editViews.add(view);
    }

    private void removeView()
    {
        for(int i = 0;i<editViews.size();i++)
        {
            View view = editViews.get(i);
            linearLayout1.removeView(view);
        }

    }



}


